<?php

class transactionActions extends sfActions {

    public function preExecute() {
        date_default_timezone_set(AppTools::TIMEZONE);
    }

    // TRANSACTION
    public function executeTransactionListData(sfWebRequest $request) {
        $start = $request->getParameter('jtStartIndex', 0);
        $length = $request->getParameter('jtPageSize', AppTools::DEFAULT_PER_PAGE);
        $sorting = $request->getParameter('jtSorting', "t.id ASC");
        $isIncome = $request->getParameter('is_income', 0);
        $userId = $request->getParameter('user_id', 0);
        $storeId = $request->getParameter('store_id', 0);
        $categoryId = $request->getParameter('cat_id', 0);
        $productId = $request->getParameter('prod_id', 0);
        $customerPhone = $request->getParameter('customer_phone', '');
        $dateBegin = $request->getParameter('date_begin', date('Y-m-d'));
        $dateEnd = $request->getParameter('date_end', date('Y-m-d'));

        $res = TransactionTable::getTransactionList($isIncome, $userId, $storeId, $dateBegin, $dateEnd, $categoryId, $productId, $sorting, $start, $length, $customerPhone);

        $result = array();
        $result['Result'] = "OK";
        $result['Records'] = $res['rows'];
        $result['TotalRecordCount'] = $res['numrows'];

        return $this->renderText(json_encode($result));
    }

    public function executeTransactionDetails(sfWebRequest $request) {
        $transId = $request->getParameter('id');
        $res = TransactionTable::getTransactionDetails($transId);

        $result = array();
        $result['Result'] = "OK";
        $result['Records'] = $res;

        return $this->renderText(json_encode($result));
    }

    public function executeTransfer(sfWebRequest $request) {
        $date = $request->getParameter('date', date('Y-m-d'));
        $storeIdFrom = $request->getParameter('store_id_from', 0);
        $storeIdTo = $request->getParameter('store_id_to', 0);
        $userIdFrom = $request->getParameter('user_id_from', 0);
        $userIdTo = $request->getParameter('user_id_to', 0);
        $items = $request->getParameter('items', array());
        $stores = StoreTable::getForSelect();
        $categories = CategoryTable::getForSelect();

        if ($request->isMethod('post')) {
            $errors = array();
            $userFrom = UserTable::retrieveByPk($userIdFrom);
            $userTo = UserTable::retrieveByPk($userIdTo);
            if (!AppTools::validateDate($date)) {
                $errors[] = 'Огноо буруу байна';
            }
            if ($storeIdFrom == 0 || $storeIdTo == 0) {
                $errors[] = 'Та шилжилт хийх салбаруудыг сонгоно уу';
            }
            if ($storeIdFrom == $storeIdTo) {
                $errors[] = 'Нэг салбар дотор шилжүүлэх хийх шаардлагагүй';
            }
            if ($userIdFrom == 0 || $userIdTo == 0) {
                $errors[] = 'Та шилжилт хийх салбаруудын ажилтнуудыг сонгоно уу';
            }
            if (!$userFrom || !$userTo || !$userFrom->is_active || !$userTo->is_active) {
                $errors[] = 'Ажилтан олдсонгүй. Эсвэл ажилтан халагдсан байна';
            }
            if ($userIdFrom == $userIdTo) {
                $errors[] = 'Ажилтан өөрлүүгээ шилжүүлэг боломжгүй';
            }
            if ($storeIdFrom != $userFrom->store_id) {
                $errors[] = $userFrom->username . ' сонгосон салбарт харьялагдахгүй байна';
            }
            if ($storeIdTo != $userTo->store_id) {
                $errors[] = $userTo->username . ' сонгосон салбарт харьялагдахгүй байна';
            }
            $transactionItems = array();
            foreach ($items as $item) {
                $prod = ProductTable::retrieveByPK($item['pid']);
                if (!$prod) {
                    $errors[] = 'Бараа олдсонгүй';
                    break;
                }
                if ($item['qty'] < 1) {
                    $errors[] = 'Барааны тоо ширхэг 0 байж болохгүй.';
                    break;
                }
                $transactionItems[] = array('productId' => $item['pid'],
                    'quantity' => $item['qty'],
                    'price' => 0);
            }

            if (count($errors)) {
                $this->getUser()->setFlash('error', implode('<br>', $errors));
            } else {
                $incomeResult = TransactionTable::doTransaction(1, $userIdTo, $storeIdTo, $date, TransactionTable::TRANS_TYPE_MOTION, $userIdFrom, 0, $transactionItems, array(), 0, $userIdFrom, $storeIdFrom);
                if ($incomeResult['success']) {
                    $outcomeResult = TransactionTable::doTransaction(0, $userIdFrom, $storeIdFrom, $date, TransactionTable::TRANS_TYPE_MOTION, $userIdTo, 0, $transactionItems, array(), $incomeResult['order_id'], $userIdTo, $storeIdTo);
                    $incomeTransaction = TransactionTable::retrieveByPK($incomeResult['order_id']);
                    if ($outcomeResult['success']) {
                        if ($incomeTransaction) {
                            $incomeTransaction->linked_trans_id = $outcomeResult['order_id'];
                            $incomeTransaction->save();
                            $this->redirect('@outcome_list');
                        }
                    }
                }
                $this->getUser()->setFlash('error', 'Уучлаарай серверт алдаа гарлаа');
            }
        }

        $this->items = $items;
        $this->date = $date;
        $this->stores = $stores;
        $this->storeIdFrom = $storeIdFrom;
        $this->storeIdTo = $storeIdTo;
        $this->userIdFrom = $userIdFrom;
        $this->userIdTo = $userIdTo;
        $this->categories = $categories;
        $this->urlProduct = AppTools::getFullUrl() . '/ajax/product';
        $this->urlUser = AppTools::getFullUrl() . '/ajax/user';
    }

    // OUTCOME
    public function executeOutcomeList(sfWebRequest $request) {
        $dateBegin = $request->getParameter('dateBegin', date('Y-m-d'));
        $this->dateBegin = $dateBegin;

        $dateEnd = $request->getParameter('dateEnd', date('Y-m-d'));
        $this->dateEnd = $dateEnd;

        $storeId = $request->getParameter('storeId', 0);
        $this->storeId = $storeId;
        $this->stores = StoreTable::getForSelect();

        $userId = $request->getParameter('userId', 0);
        $this->userId = $userId;
        $this->users = UserTable::getForSelect();

        $categoryId = $request->getParameter('categoryId', 0);
        $this->categoryId = $categoryId;
        $this->categories = CategoryTable::getForSelect();

        $productId = $request->getParameter('productId', 0);
        $this->productId = $productId;

        $customerPhone = $request->getParameter('customerPhone', 0);
        $this->customerPhone = $customerPhone;

        $urlParams = array();
        $urlParams[] = "is_income=0";
        $urlParams[] = "user_id=$userId";
        $urlParams[] = "store_id=$storeId";
        $urlParams[] = "cat_id=$categoryId";
        $urlParams[] = "prod_id=$productId";
        $urlParams[] = "date_begin=$dateBegin";
        $urlParams[] = "date_end=$dateEnd";
        $urlParams[] = "customer_phone=$customerPhone";

        $this->urlTable = $this->generateUrl('transaction_list_data') . '?' . implode('&', $urlParams);
        $this->urlDetail = $this->generateUrl('transaction_details');
        $this->urlEdit = $this->generateUrl('transaction_edit');
        $this->urlRemove = $this->generateUrl('outcome_remove');
        $this->urlProduct = AppTools::getFullUrl() . '/ajax/product';
    }

    public function executeTransactionEdit(sfWebRequest $request) {
        $transactionId = (int) $request->getParameter('id');
        $transaction = TransactionTable::retrieveByPK($transactionId);
        if (!$transaction) {
            $this->getUser()->setFlash('error', 'Тухайн бичлэг олдсонгүй.');
            $this->redirect($request->getReferer());
        }

        $isIncome = $transaction->is_income;

        $transactionItems = TransactionItemTable::getByTransactionId($transactionId);
        $paymentTypes = TransactionPaymentTable::getPaymentTypes();
        $transactionPayments = TransactionPaymentTable::getByTransactionId($transactionId);

        $user = UserTable::retrieveByPk($transaction['user_id']);

        //Transaction type change is dangerous
        $transactionTypes = TransactionTable::getTransactionTypes();
        unset($transactionTypes[TransactionTable::TRANS_TYPE_SUPPLIER]);
        if ($transaction['trans_type'] == TransactionTable::TRANS_TYPE_CUSTOMER) {
            unset($transactionTypes[TransactionTable::TRANS_TYPE_MOTION]);
        } elseif ($transaction['trans_type'] == TransactionTable::TRANS_TYPE_MOTION) {
            unset($transactionTypes[TransactionTable::TRANS_TYPE_CUSTOMER]);
            unset($transactionTypes[TransactionTable::TRANS_TYPE_SERVICE]);
        }

        if ($request->isMethod('post')) {
            $transactionDate = $request->getParameter('trans_date');
            $storeId = $request->getParameter('store');
            $transactionType = (int) $request->getParameter('trans_type');
            $transactionEntityId = (int) $request->getParameter('trans_ent_id');
            $products = $request->getParameter('products');
            $payments = $request->getParameter('payments');

            #validating everything...
            if (!$transactionDate || !AppTools::validateDate($transactionDate)) {
                $this->getUser()->setFlash('error', 'Бараагүй зарлага байж болохгүй.');
                $this->redirect($request->getReferer());
            }
            if (count($products) < 1) {
                $this->getUser()->setFlash('error', 'Бараагүй зарлага байж болохгүй.');
                $this->redirect($request->getReferer());
            }
            $prodTotal = 0;
            foreach ($products as $prod) {
                if (!is_numeric($prod['pid']) || !is_numeric($prod['qty']) || !is_numeric($prod['price'])) {
                    $this->getUser()->setFlash('error', 'Барааны үнийн дүн болон тоо ширхэг гэсэн талбарт <b>тоон утга</b> оруулна уу.');
                    $this->redirect($request->getReferer());
                }
                if ($prod['qty'] < 1) {
                    $this->getUser()->setFlash('error', 'Барааны тоо ширхэгийг 0-ээс илүү тоо оруулна уу');
                    $this->redirect($request->getReferer());
                }
                $prodTotal += $prod['price'];
            }
            $paymentTotal = 0;


            foreach ($payments as $paymentTypeId => $amount) {
                if (!array_key_exists($paymentTypeId, $paymentTypes)) {
                    $this->getUser()->setFlash('error', 'Төлбөрийн хэлбэр буруу байна');
                    $this->redirect($request->getReferer());
                }
                $paymentTotal += $amount;
            }

            if ($paymentTotal != $prodTotal) {
                $this->getUser()->setFlash('error', 'Төлбөрийн хэлбэр буруу байна');
                $this->redirect($request->getReferer());
            }

            #processing...
            $invCalcArray = array(); //used for inventory calculations
            $invCalcArray[] = array('userId' => $transaction->user_id, 'storeId' => $transaction->store_id);
            if ($storeId != $transaction->store_id) {
                $invCalcArray[] = array('userId' => $transaction->user_id, 'storeId' => $storeId);
            }
            if ($transactionType == TransactionTable::TRANS_TYPE_MOTION) {
                $invCalcArray[] = array('userId' => $transaction->user_id, 'storeId' => $transaction->store_id);
                if ($transactionEntityId != $transaction->trans_entity_id) {
                    $invCalcArray[] = array('userId' => $transaction->user_id, 'storeId' => $storeId);
                }
            }

            $transaction->store_id = $storeId;
            $transaction->trans_date = $transactionDate;
            if ($transactionType) {
                $transaction->trans_type = $transactionType;
            }
            if ($transactionEntityId) {
                $transaction->trans_entity_id = $transactionEntityId;
            }
            $transaction->total_price = $prodTotal;
            $transaction->save();

            TransactionItemTable::removeByTransationId($transactionId);
            TransactionPaymentTable::removeByTransationId($transactionId);

            foreach ($products as $item) {
                $transactionItem = new TransactionItem();
                $transactionItem->trans_id = $transactionId;
                $transactionItem->product_id = $item['pid'];
                if ($isIncome) {
                    $transactionItem->quantity = $item['qty'];
                } else {
                    $transactionItem->quantity = $item['qty'] * -1;
                }
                $transactionItem->price = $item['price'];
                $transactionItem->created_at = date('Y-m-d H:i:s');
                $transactionItem->save();
            }

            foreach ($payments as $paymentMethodId => $amount) {
                if ($amount > 0) {
                    $transactionPayment = new TransactionPayment();
                    $transactionPayment->trans_id = $transactionId;
                    $transactionPayment->payment_method_id = $paymentMethodId;
                    $transactionPayment->amount = $amount;
                    $transactionPayment->created_at = date('Y-m-d H:i:s');
                    $transactionPayment->save();
                }
            }

            foreach ($products as $prod) {
                foreach ($invCalcArray as $invCalc) {
                    InventoryTable::calcInventoryItem($invCalc['userId'], $invCalc['storeId'], $prod['pid'], $transaction->trans_date);
                }
            }

            $this->getUser()->setFlash('succes', 'Амжилттай заслаа');
            if ($isIncome) {
                $this->redirect('@income_list');
            } else {
                $this->redirect('@outcome_list');
            }
        }

        $this->transaction = $transaction;
        $this->transactionItems = $transactionItems;
        $this->transactionPayments = $transactionPayments;
        $this->transactionTypes = $transactionTypes;
        $this->paymentTypes = $paymentTypes;
        $this->categories = CategoryTable::getForSelect();
        $this->stores = StoreTable::getForSelect();
        $this->user = $user;
        $this->isIncome = $isIncome;

        $this->urlProduct = AppTools::getFullUrl() . '/ajax/product';
        $this->urlCustomer = AppTools::getFullUrl() . '/ajax/customer';
        $this->urlUser = AppTools::getFullUrl() . '/ajax/user';
        $this->urlManufacturer = AppTools::getFullUrl() . '/ajax/manufacturer';
    }

    // INCOME
    public function executeIncomeList(sfWebRequest $request) {
        $dateBegin = $request->getParameter('dateBegin', date('Y-m-d'));
        $this->dateBegin = $dateBegin;

        $dateEnd = $request->getParameter('dateEnd', date('Y-m-d'));
        $this->dateEnd = $dateEnd;

        $storeId = $request->getParameter('storeId', 0);
        $this->storeId = $storeId;
        $this->stores = StoreTable::getForSelect();

        $userId = $request->getParameter('userId', 0);
        $this->userId = $userId;
        $this->users = UserTable::getForSelect();

        $categoryId = $request->getParameter('categoryId', 0);
        $this->categoryId = $categoryId;
        $this->categories = CategoryTable::getForSelect();

        $productId = $request->getParameter('productId', 0);
        $this->productId = $productId;

        $urlParams = array();
        $urlParams[] = "is_income=1";
        $urlParams[] = "user_id=$userId";
        $urlParams[] = "store_id=$storeId";
        $urlParams[] = "cat_id=$categoryId";
        $urlParams[] = "prod_id=$productId";
        $urlParams[] = "date_begin=$dateBegin";
        $urlParams[] = "date_end=$dateEnd";

        $this->urlTable = $this->generateUrl('transaction_list_data') . '?' . implode('&', $urlParams);
        $this->urlDetail = $this->generateUrl('transaction_details');
        $this->urlEdit = $this->generateUrl('transaction_edit');
        $this->urlRemove = $this->generateUrl('income_remove');
        $this->urlProduct = AppTools::getFullUrl() . '/ajax/product';
    }

    public function executeIncomeEdit(sfWebRequest $request) {
        $categoryId = (int) $request->getParameter('category_id', 0);
        $categories = CategoryTable::getForSelect();
        $productId = (int) $request->getParameter('product_id', 0);
        $incomeDate = $request->getParameter('income_date', date('Y-m-d'));
        $transactionTypeId = (int) $request->getParameter('trans_type_id', TransactionTable::TRANS_TYPE_SUPPLIER);
        $transactionEntityId = (int) $request->getParameter('trans_ent_id', 0);

        $userId = $this->getUser()->getId();

        $userItems = TransInBasketItemTable::getUserItems($userId);
        $transactionTypes = TransactionTable::getTransactionTypes();
        unset($transactionTypes[TransactionTable::TRANS_TYPE_MOTION]);
        unset($transactionTypes[TransactionTable::TRANS_TYPE_SERVICE]);

        $this->userItems = $userItems;
        $this->categories = $categories;
        $this->categoryId = $categoryId;
        $this->productId = $productId;
        $this->incomeDate = $incomeDate;
        $this->transactionTypes = $transactionTypes;
        $this->transactionTypeId = $transactionTypeId;
        $this->transactionEntityId = $transactionEntityId;
        $this->urlProduct = AppTools::getFullUrl() . '/ajax/product';
        $this->urlCustomer = AppTools::getFullUrl() . '/ajax/customer';
        $this->urlUser = AppTools::getFullUrl() . '/ajax/user';
        $this->urlManufacturer = AppTools::getFullUrl() . '/ajax/manufacturer';
    }

    public function executeIncomeBasketItemAdd(sfWebRequest $request) {
        $userId = $this->getUser()->getId();
        $category = (int) $request->getParameter('category', 0);
        $product = (int) $request->getParameter('product', 0);
        $quantity = (int) $request->getParameter('quantity', 0);

        if (!$product) {
            $this->getUser()->setFlash('error', 'Бараа сонгоно уу');
            $this->redirect("@income_edit?category_id=$category");
        }
        if (!$quantity) {
            $this->getUser()->setFlash('error', 'Сагсанд хийх барааны тоог оруулна уу');
            $this->redirect("@income_edit?category_id=$category&product_id=$product");
        }

        $userItem = TransInBasketItemTable::retrieveByUserProduct($userId, $product);
        if ($userItem) {
            $this->getUser()->setFlash('warning', 'Сагсанд нэг барааг 2 удаа хийсэн тул тоон дүнг нэмэгдүүллээ');
            $userItem['quantity'] += $quantity;
        } else {
            $userItem = new TransInBasketItem();
            $userItem['user_id'] = $userId;
            $userItem['quantity'] = $quantity;
            $userItem['product_id'] = $product;
        }
        $userItem->save();

        $this->redirect('@income_edit');
    }

    public function executeIncomeBasketItemDelete(sfWebRequest $request) {
        $id = $request->getParameter('id');

        $item = TransInBasketItemTable::retrieveByPk($id);
        if ($item) {
            $item->delete();
        } else {
            $this->getUser()->setFlash('error', 'Сагсанд ийм бараа алга.');
        }
        $this->redirect("@income_edit");
    }

    public function executeIncomeAdd(sfWebRequest $request) {
        $incomeDate = $request->getParameter('income_date', null);
        $transType = $request->getParameter('trans_type', 0);
        $transEntId = $request->getParameter('trans_ent_id', 0);

        $userId = $this->getUser()->getId();

        $userItems = TransInBasketItemTable::getUserItems($userId);

        $urlParams = array();
        $urlParams[] = "income_date=$incomeDate";
        $urlParams[] = "trans_type_id=$transType";
        $urlParams[] = "trans_ent_id=$transEntId";

        $redirectUrl = $this->generateUrl('income_edit') . '?' . implode('&', $urlParams);

        if (!count($userItems)) {
            $this->getUser()->setFlash('error', 'Сагс хоосон байна');
            $this->redirect($redirectUrl);
        }
        if ($incomeDate > date('Y-m-d')) {
            $this->getUser()->setFlash('error', "Орлогын огноо нь <b>" . date('Y-m-d') . "</b> өдрөөс өмнө байх ёстой.");
            $this->redirect($redirectUrl);
        }
        if ($transType == TransactionTable::TRANS_TYPE_SUPPLIER && $transEntId == 0) {
            $this->getUser()->setFlash('error', "Та үйлдвэрлэгч компани сонгоно уу.");
            $this->redirect($redirectUrl);
        }
        $user = UserTable::retrieveByPk($userId);
        if (!$user['store_id']) {
            $this->getUser()->setFlash('error', "Та салбарт харъяалагдаагүй байна.");
            $this->redirect($redirectUrl);
        }

        #create items for transaction
        $items = array();
        foreach ($userItems as $i) {
            $item = array();
            $item['productId'] = $i['product_id'];
            $item['quantity'] = $i['quantity'];
            $item['price'] = 0;
            $items[] = $item;
        }

        $res = TransactionTable::doTransaction(1, $userId, $user['store_id'], $incomeDate, $transType, $transEntId, 0, $items, array());

        TransInBasketItemTable::removeByUserId($userId);

        $this->getUser()->setFlash('success', "Амжилттай орлого нэмлээ.");
        $this->redirect("@income_list");
    }

    public function executeIncomeDelete(sfWebRequest $request) {
        print_r($_REQUEST);
        die();
    }

}
